package apps.softtech.fastmarket;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.provider.MediaStore.MediaColumns;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import apps.softtech.CustomView.ViewLoadContentRequireFieldProduct;
import apps.softtech.Utility.HttpRequest;
import apps.softtech.Utility.MultipartRequest;
import apps.softtech.fastmarket.model.ViewLoadItem;

public class ActivityCreateProduct extends Activity {

	final int MODE_CHOOSE_IMAGE = 0;

	final int REQUEST_CAMERA = 1;
	final int SELECT_FILE = 2;

	ViewLoadContentRequireFieldProduct parentView;

	Context mContext;

	int typeAction;
	ViewLoadItem viewSelected;

	private String mNameProduct = "cuc cut ga";
	private String mPrice = "2 ty vnd";
	String regId = "APA91bG_LYvK90WeEJW17gYqJRPcNouePVNTHCfuowIGmYnbkf1WIABAh0pw_Ue4nZ1EOiboxzEQPZli8TdZ_ObWw19ZMhaAhPVm8MtUp02ftOVU81UhbiWdB95yZLvbuPPCiZ7eB7CX_BBWoyCu7BJ0puY7P-jdWOobtBnQ5tbPTbTDutegzn0";
	int categoryId = 24;
	
	Button btnCreateProduct;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_create_product);
		mContext = this;
		
		
		taskGetRequireField.execute(null, null, null);
		// tsakUploadFile.execute(null,null,null);

	}
	
	/**
	 * set id
	 */
	void setId(){
		parentView = (ViewLoadContentRequireFieldProduct) findViewById(R.id.parentView);

		btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);
	}
	
	/**
	 * set function for all view in app
	 */
	void setFunction() {
		
		btnCreateProduct.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(parentView.checkValidatePairListResult()){
					taskCreateProduct.execute(null,null,null);
				}else{
					Toast.makeText(mContext, "douma thieu cmn truong require roi", Toast.LENGTH_SHORT).show();
				}
				
			}
		});
		
		for (int i = 0; i < parentView.getListLoader().size(); i++) {
			switch (parentView.getListLoader().get(i).getTag()
					.getTagValueType()) {
			case ViewLoadContentRequireFieldProduct.MODE_EDIT_TEXT:
				setFunctionModeEdittext(parentView.getListLoader().get(i));
				break;
			case ViewLoadContentRequireFieldProduct.MODE_IMAGE_VIEW:
				setFunctionModeImageMode(parentView.getListLoader().get(i));
				break;
			default:
				break;
			}
		}
	}

	/**
	 * set function for viewloaditem type image
	 * @param item
	 */
	void setFunctionModeImageMode(final ViewLoadItem item) {
		item.getView().setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				setSelectedView(item, MODE_CHOOSE_IMAGE);
				selectImage();
			}
		});
	}

	/**
	 * set function for viewloaditem type edittext
	 * @param item
	 */
	void setFunctionModeEdittext(final ViewLoadItem item) {
		((EditText) item.getView()).addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				item.setValue(s.toString());

			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (data == null) {
			Log.e(mContext.getClass().getName(), "data result null");
			return;
		}
		if (resultCode == RESULT_OK) {
			if (requestCode == REQUEST_CAMERA) {
				Log.e(mContext.getClass().getName(), "request camera");
				loadImageFromCameraResult(data);
			} else if (requestCode == SELECT_FILE) {
				Log.e(mContext.getClass().getName(), "select file");
				loadImageFromGarelly(data);
			}
		}
	}

	/**
	 * set selected view load item  
	 * @param view
	 * @param mode
	 */
	void setSelectedView(ViewLoadItem view, int mode) {
		typeAction = mode;
		viewSelected = view;
	}

	/**
	 * show dialog select image
	 * -camera
	 * -choose library
	 * -cancel
	 */
	private void selectImage() {
		final CharSequence[] items = { "Take Photo", "Choose from Library",
				"Cancel" };

		AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
		builder.setTitle("Add Photo!");
		builder.setItems(items, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int item) {
				if (items[item].equals("Take Photo")) {
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					startActivityForResult(intent, REQUEST_CAMERA);
				} else if (items[item].equals("Choose from Library")) {
					Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
					intent.setType("image/*");
					if (intent.resolveActivity(getPackageManager()) != null) {
						startActivityForResult(intent, SELECT_FILE);
					}
				} else if (items[item].equals("Cancel")) {
					dialog.dismiss();
				}
			}
		});
		builder.show();
	}

	/**
	 * get path from uri
	 * @param uri
	 * @param activity
	 * @return
	 */
	public String getPath(Uri uri, Activity activity) {
		String[] projection = { MediaColumns.DATA };
		Cursor cursor = activity
				.managedQuery(uri, projection, null, null, null);
		int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	/**
	 * get image uri
	 * @param inContext
	 * @param inImage
	 * @return
	 */
	public Uri getImageUri(Context inContext, Bitmap inImage) {
		ByteArrayOutputStream bytes = new ByteArrayOutputStream();
		inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
		String path = Images.Media.insertImage(inContext.getContentResolver(),
				inImage, "Title", null);
		return Uri.parse(path);
	}

	/**
	 * load image from camera result
	 * @param data
	 */
	public void loadImageFromCameraResult(Intent data) {
		Bitmap photo = (Bitmap) data.getExtras().get("data");
		((ImageView) viewSelected.getView()).setImageBitmap(photo);

		// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
		Uri tempUri = getImageUri(getApplicationContext(), photo);

		// CALL THIS METHOD TO GET THE ACTUAL PATH
		String imagePath = getRealPathFromURI(tempUri);
		viewSelected.setValue(imagePath);

		Log.e(mContext.getClass().getName(), imagePath);
	}

	/**
	 * get real path from uri
	 * @param uri
	 * @return
	 */
	public String getRealPathFromURI(Uri uri) {
		Cursor cursor = getContentResolver().query(uri, null, null, null, null);
		cursor.moveToFirst();
		int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
		return cursor.getString(idx);
	}

	/**
	 * load image from garelly
	 * @param data
	 */
	void loadImageFromGarelly(Intent data) {
		Uri selectedImageUri = data.getData();

		String tempPath = getPath(selectedImageUri, ActivityCreateProduct.this);
		viewSelected.setValue(tempPath);
		Uri fullPhotoUri = data.getData();
		Bitmap bitmap;
		try {
			bitmap = MediaStore.Images.Media.getBitmap(
					this.getContentResolver(), fullPhotoUri);
			if (bitmap != null) {
				try {
					Bitmap bmtemp = Bitmap.createScaledBitmap(bitmap, 250, 250,
							true);
					((ImageView) viewSelected.getView()).setImageBitmap(bmtemp);
				} catch (OutOfMemoryError oe) {
					oe.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

		} catch (FileNotFoundException e) {

			e.printStackTrace();
		} catch (IOException e) {

			e.printStackTrace();
		} catch (OutOfMemoryError oe) {
			oe.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * task get require field from server
	 */
	AsyncTask<Void, Void, String> taskGetRequireField = new AsyncTask<Void, Void, String>() {

		@Override
		protected String doInBackground(Void... params) {
			try {
				String url = "http://192.168.1.11/fastmarket/index.php/category/get_list_infor_tag_by_category";

				JSONObject object = new JSONObject();
				object.put(
						"st_GcmId", regId
						);
				object.put("st_CategoryId", categoryId );

				ArrayList<NameValuePair> pairList = new ArrayList<NameValuePair>();
				pairList.add(new BasicNameValuePair("data", object.toString()));

				HttpRequest request = new HttpRequest();
				return request.makeServiceCall(url, HttpRequest.POST, pairList);
			} catch (Exception e) {
				e.printStackTrace();
			}

			return "";

		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			parentView.showProgressbar(mContext);
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			parentView.hideProgressbar();
			if (result == null || result.equals(null) || result.length() == 0) {
				return;
			}
			try {
				JSONObject resultobject = new JSONObject(result);
				JSONArray array = resultobject.getJSONArray("data");
				parentView.setListLoaderFromJSONArray(array);
				parentView.addLayerRequireFromArray();
				setFunction();
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

	};

	/**
	 * task upload file
	 */
	AsyncTask<Void, Void, String> taskUploadFile = new AsyncTask<Void, Void, String>() {

		@Override
		protected String doInBackground(Void... params) {
			String url = "http://192.168.1.11/fastmarket/index.php/upload/do_upload_product";
			// setup params
			Map<String, String> listParams = new HashMap<String, String>(2);
			listParams.put("foo", "chymdada");
			listParams.put("bar", "conchymnon");
			MultipartRequest part = new MultipartRequest();
			String result = part.multipartRequest(url, listParams,
					Environment.getExternalStorageDirectory()
							+ "/COCA_SIGN/temp_share.jpg", "userfile",
					"image/jpeg");
			return result;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			Log.e("CHYM CHICH BONG", "BE TEO TEO " + result);
		}

	};
	
	/**
	 * task create product
	 */
	AsyncTask<Void, Void, String> taskCreateProduct = new AsyncTask<Void, Void, String>(){

		@Override
		protected String doInBackground(Void... params) {
			try {
				String url = "http://192.168.1.11/fastmarket/index.php/product/create_product";
				
				
				HttpRequest request = new HttpRequest();
				List<NameValuePair> listPair = new ArrayList<NameValuePair>();
				
				JSONObject object = new JSONObject();
				object.put("st_GcmId", regId);
				object.put("st_CategoryId" , categoryId );
				object.put("st_ProductName", mNameProduct);
				object.put("st_Price" , mPrice);
				object.put("information" , parentView.pairListToJSON() );
				listPair.add(new BasicNameValuePair("data", object.toString()));
				
				String result = request.makeServiceCall(url, HttpRequest.POST, listPair);
				return result;
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			return null;
		}
		
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			Log.e("CHYM CHICH BONG", "BE TEO TEO " + result);
			
		}
		
	};
	
}
